import { defineStore } from 'pinia';
import { getCartList,addProductToCart, updateProductNum, deleteCartProductById } from '@/api/CartService';
import { useProductStore } from './productStore';



export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
  }),
  getters: {
    totalPrice: (state) => {
           return state.items.reduce((total, item) => {
            return total + item.price * item.quantity
      }, 0)
    },
  },
  actions: {
    async fetchData() {

      const productStore = useProductStore();
      await productStore.fetchProducts();
      var productList = productStore.products;
      var cartItem = await getCartList();
      
      
      this.items = cartItem.map((element)=>{
        let productInfo =productList.find(product=>product.id===element.productId);
        if(productInfo){
          return{
            ...element,
            name:productInfo.name,
            price:productInfo.price
          }
        }
        else{
          return element;
        }
          })





    },






    async addItem(item) {
      const existingItem = this.items.find(i => i.id === item.id);
      if (existingItem) {
        existingItem.quantity += item.quantity;
        const cart = {
          productId:item.id,
          quantity:existingItem.quantity
        }
        await updateProductNum(cart);


      } else {

        this.items.push(item);
        const cart = {
          productId:item.id,
          quantity:item.quantity,
        }

        await addProductToCart(cart);
      }
    },
    async removeItem(id) {
      const index = this.items.findIndex(i => i.id === id);
      if (index > -1) {
        this.items.splice(index, 1);
        //删除数据库里的信息
        await deleteCartProductById(id);


      }
    },
    async updateItemQuantity(id, quantity) {
      const item = this.items.find(i => i.id === id);
      if (item) {
        // console.log("修改数量")
       
        item.quantity = quantity;
        const cart = {
          productId:item.id,
          quantity:item.quantity
        }
        await updateProductNum(cart);
      }
    },
  },
});
